package com.bokey.service.Impl;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
public class SendEmailService {
    @Resource
    private JavaMailSenderImpl javaMailSender;
    @Value("${spring.mail.username}") // 配置发件人的qq邮箱
    private String form;
    // 发送模板邮件
    public void sendTemplateEmail(String to,String subject,String content) {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            // 使用MimeMessage帮助类，并设置multipart多部件使用为true
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(form);
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(content,true);
            // 发送邮件                         ↑ mimeMessageHelper.setText的第二个参数表示该邮件内容是否为html页面
            javaMailSender.send(mimeMessage);
            System.out.println("邮件发送成功!");
        }catch (MessagingException e) {
            System.out.println("邮件发送失败!");
            e.printStackTrace();
        }
    }
}
